package chapter3to7.src.main.java.com.kaikeba.concurrent;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 吴世凯
 * 邮箱：
 * 日期：3/21/2021
 */
public class ThreadPoolDemo {


    static   ExecutorService executorService ;

    public static void main(String[] args) {

       // executorService = Executors.newFixedThreadPool(10);
       // test(executorService);  //slow


       //  executorService = Executors.newSingleThreadExecutor();
       //  test(executorService); //very slow


        executorService = Executors.newCachedThreadPool();
        test(executorService); //fast

    }

    public static void test( ExecutorService executorService){




        for (int i = 0; i < 100; i++) {
            executorService.execute(new Task(i));
        }
        executorService.shutdown();
    }







    private static class Task implements Runnable{


        int i = 0 ;

        public Task(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " --- " + i);

            try {
                Thread.sleep(1000L);

            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}



